package com.leenleda.ips.util;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.Log;

import com.leenleda.ips.entity.BaseEntity;
import com.leenleda.ips.entity.MediaEntity;
import com.leenleda.ips.net.AEvent;
import com.leenleda.ips.receiver.Constant;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;

public class FileUtils {


    private static String tag = "FileUtils";

    private static String getCachePath() {
        String path = null;
        try {
            path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/LELDIPS/";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i(tag, "getCrashFilePath: " + path);
        return path;
    }

    /**
     * 设备id
     */
    public static String getDeviceMac(){
        String uuid = Utils.getStringValue(UShared.getString(Constant.ANDROID_ID));
        LogUtils.i(tag, "====getDeviceMac==1==" + uuid );
        String path = getCachePath() + Constant.PUBLISH_FILE_MAC;         //大邑中医院

        File file = new File(path);
        if (file.exists()){
            try {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
                BufferedReader br = new BufferedReader(isr);

                String mimeTypeLine = null ;
                String uuidTT = "";
                while ((mimeTypeLine = br.readLine()) != null)
                    uuidTT = uuidTT+mimeTypeLine;
                LogUtils.i(tag, "====getDeviceMac===11=" + uuidTT);
                LogUtils.i(tag, "====getDeviceMac===12=" + uuid);
                if (uuidTT.isEmpty() || uuidTT.equalsIgnoreCase("save_wrong")){
                    LogUtils.i(tag, "====getDeviceMac===13=" + uuid);
                    file.delete();
                    return getDeviceMac();
                }
                UShared.putString(Constant.ANDROID_ID, uuidTT);
                if (!uuid.isEmpty()){
                    return uuid;
                }
                return uuidTT;
            } catch (IOException e) {
                e.printStackTrace();
            }
            LogUtils.i(tag, "=====getDeviceMac=====9=" + file.exists());
            file.delete();

        }
        if (uuid.isEmpty()) {
            uuid =  "uuid_" + UUID.randomUUID();
        }
        LogUtils.i(tag, "====getDeviceMac==23==" + uuid );
        if (uuid.equals("uuid_a1188c26-a4c0-4d8c-a0ff-999f806bc489")){
            uuid =  "uuid_" + UUID.randomUUID();
        }
        saveUUID(path, uuid);

        return uuid;
    }

    private static void saveUUID(String path, String uuid){
        UShared.putString(Constant.ANDROID_ID, uuid);
        try {
            FileWriter writer = new FileWriter(path);
            writer.write(uuid);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            LogUtils.i(tag, "====getDeviceMac==Exception==" + e );
            e.printStackTrace();
        }
    }

//===================*******PUBLISH_FILE_IP*******=================================
    public static void setServeIp(String serveIp){
        LogUtils.i(tag, "====info===setServeIp=" + serveIp);
        if (!Utils.isBoolIp(serveIp))
            return;
        String path = getCachePath() + Constant.PUBLISH_FILE_IP;
        File file = new File(path);
        LogUtils.i(tag, "=====setServeIp=====8=" + file.exists());
        if (file.exists())
            file.delete();
        UShared.putString(Constant.PUBLISH_IP, serveIp);
        try {
            FileWriter writer = new FileWriter(path);
            writer.write(serveIp);
            writer.flush();
            writer.close();
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取serviceIP
     */
    public static String getServiceIp(){
        String ipServer = Utils.getStringValue(UShared.getString(Constant.PUBLISH_IP));
        LogUtils.i(tag, "====exists====" + ipServer );
        if (!ipServer.trim().isEmpty())
            return ipServer;
        String path = getCachePath() + Constant.PUBLISH_FILE_IP;
        File file = new File(path);
        if (file.exists()){
            try {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
                BufferedReader br = new BufferedReader(isr);

                String mimeTypeLine = null ;
                while ((mimeTypeLine = br.readLine()) != null) {
                    ipServer = ipServer+mimeTypeLine;
                }
                LogUtils.i(tag, "====ipServer===1=" + ipServer);
                UShared.putString(Constant.PUBLISH_IP, ipServer);
                return ipServer;
            } catch (IOException e) {
                e.printStackTrace();
            }
            LogUtils.i(tag, "=====删除文件=====7=");
            file.delete();
        } else {
            BaseEntity aa = BaseUtils.getBase();    //同步version30以下数据
            LogUtils.i(tag, "====exists==aa==" + aa  );
            if (aa != null){
                String ip = aa.getServiceIp();
                String mac = aa.getDeviceMac();
                UShared.putString(Constant.ANDROID_ID, mac);
                setServeIp(ip);
                return ip;
            }
        }
        return "";
    }

    /**
     * 删除文件
     */
    public static boolean deleteFile(String path) {
        if (path == null || path.trim().length() == 0) {
            return true;
        }

        File file = new File(path);
        if (!file.exists()) {
            return true;
        }
        if (file.isFile()) {
            LogUtils.i(tag, "=====删除文件=====5=");
            return file.delete();
        }
        if (!file.isDirectory()) {
            return false;
        }
        for (File f : file.listFiles()) {
            if (f.isFile()) {
                LogUtils.i(tag, "=====删除文件=====6=");
                f.delete();
            } else if (f.isDirectory()) {
                deleteFile(f.getAbsolutePath());
            }
        }
        LogUtils.i(tag, "=====删除文件=====7=");
        return file.delete();
    }

    /**
     * 删除空文件夹
     * @param file
     */
    public static void emptyFolder(File file) {
        LogUtils.e(tag, "===emptyFolder=**file***000****" + file);
        if (!file.exists())
            return;
        File[] files = file.listFiles();
        LogUtils.e(tag, "===emptyFolder=**file***length****" + files.length);
        if (files.length == 0){
            LogUtils.i(tag, "=====删除文件=====4=" + files.length);
            file.delete();
            return;
        }
        for (File file2 : files) {
            if (file2.isDirectory() && file2.length() == 0) {
                LogUtils.i(tag, "=====删除文件=====3=" + file2);
                file2.delete();
            } else if (file2.isDirectory()) {
                LogUtils.e(tag, "===emptyFolder=**file****1111***" + file2);
                emptyFolder(file2);
            }
        }
    }

    /**
     * 获取文件夹大小
     */
    public static long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) size = size + getFolderSize(fileList[i]);
                else size = size + fileList[i].length();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.e("SLDVNLSDV", "======size====" + size);
        return (long) (size /  (1024.0 * 1024.0));
    }

    /**
     * 删除子目录及父目录   包含本目录
     */
    public static boolean deleteALl(File file) {
        if (!file.exists())
            return true;
        if (file.isDirectory()){
            for (File fi : file.listFiles()){
                if (fi.isDirectory()){
                    deleteALl(fi);
                } else {
                    LogUtils.i("SLDVNLSDV", "=====删除文件=====1=" + file.getName());
                    fi.delete();
                }
            }
            Log.e("SLDVNLSDV", "=====***文件夹***======" + file.listFiles().length);
        }
        LogUtils.i("SLDVNLSDV", "=====删除文件=====2=" + file.getAbsolutePath());
        return file.delete();
    }

    /**
     * 删除子目录  不包含本目录
     * @param file
     */
    public static boolean deleteChild(File file){
        if (!file.exists())
            return false;
        if (!file.isDirectory())
            return false;
        for (File fi : file.listFiles()){
            if (!deleteALl(fi))
                return false;
        }
        return true;
    }

    /**
     * 获取可用空间
     */
    public static String getAvailSpace(Context context, String path) {
        StatFs stat = new StatFs(path); // 获取可用空间
        long availableBlocks = stat.getAvailableBlocks();// 获取可用存储块数量
        long blockSize = stat.getBlockSize(); // 每个存储块的大小
        long availSize = availableBlocks * blockSize;// 可用存储空间
        // Integer.MAX_VALUE 可以表示2G大小, 2G太少, 需要用Long
        return Formatter.formatFileSize(context, availSize);// 将字节转为带有相应单位(MB, G)的字符串
    }


    public static long getFileSize(MediaEntity entity){
        float fileSize = 0;
        String sizeStr = entity.getFilesize()
                .replace("k", "K")
                .replace("m", "M")
                .replace("g", "G")
                .replace("b", "B");
        if (sizeStr.contains("KB")){
            fileSize = Integer.parseInt(sizeStr.replace("KB", "")) / 1024.0f;
        } else if (sizeStr.contains("MB")){
            fileSize = Integer.parseInt(sizeStr.replace("MB", ""));
        } else if (sizeStr.contains("GB")){
            fileSize = Integer.parseInt(sizeStr.replace("GB", "")) * 1024.0f;
        }
        return (long) fileSize;
    }

    /**
     * 文件复制
     */
    public static boolean copyFile(String path, String fileName) {
        try {
            File oldFile = new File(path);
            if (!oldFile.exists())
                return false;
            File videoFile = new File(getPath(Constant.CACHE_FOLDER), fileName);

            FileInputStream fileInputStream = new FileInputStream(path);
            FileOutputStream fileOutputStream = new FileOutputStream(videoFile);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @return 获取文件路径
     */
    public static String getPath(String folderName) {
        String path = Environment.getExternalStorageDirectory() + "/mediaCache/" + folderName + "/";
        File file = new File(path);
        if (file.mkdirs())
            return path;
        return path;
//        if (BaseActivity.getForegroundActivity() == null)
//            return "";
//        return getSDPath(BaseActivity.getForegroundActivity(), folderName);
    }


//    public static String getPath(String folderName) {
//        String path = Environment.getExternalStorageDirectory() + "/mediaCache/" + folderName + "/";
//        File file = new File(path);
//        if (file.mkdirs())
//            return path;
//        return path;
//    }


    public static String getSDPath(Context context, String folderName) {
        String sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
        if (sdCardExist) {
            if (Build.VERSION.SDK_INT>=29){//Android10之后
                sdDir = context.getExternalFilesDir(null).getPath();
                Log.e("--getCachePath--", "=====sdDir===1====" + sdDir);
            }else {
                sdDir = Environment.getExternalStorageDirectory().getPath() + "/mediaCache/" + folderName + "/";// 获取SD卡根目录
                File file = new File(sdDir);
                if (!file.exists()) {
                    file.mkdirs();
                }
                Log.e("--getCachePath--", "=====sdDir===2====" + sdDir);
            }
        } else {
            sdDir = Environment.getRootDirectory().getPath();// 获取跟目录
            Log.e("--getCachePath--", "=====sdDir==3=====" + sdDir);
        }
        return sdDir;
    }

    public static long getFreeSize(){
        StatFs state = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
        long blockSize = state.getBlockSize();
        long blockCount = state.getBlockCount();
        long availableCount = state.getAvailableBlocks();
        long totalSpace = blockCount * blockSize / 1024 / 1024; /* 存储空间大小 in MB */
        long freeSpace = availableCount * blockSize / 1024 / 1024; /* 可用的存储空间大小 in MB */
//        ILog.e(tag, "=====totalSpace======" + totalSpace);
//        ILog.e(tag, "=====freeSpace======" + freeSpace);
        return freeSpace;
    }

    public static String getVideoUrl(MediaEntity entity, String target){
        String filePath = "";
        String path = FileUtils.getPath(Constant.CACHE_FOLDER);
        File file = new File(path);
        if (file.isDirectory()){
            for (File fi : file.listFiles()){
                String name = fi.getName();
                String[] aa = name
//                        .replace(".mp4", "")
//                        .replace(".png", "")
                        .replace(target, "")
                        .split("_");
                if (aa.length > 1){
                    if (aa[aa.length - 1].equals(entity.getId() + "")){
                        filePath = path + "/" + name;
                        return filePath;
                    }
                }
            }
        }
        Log.e(tag, "=====mVideoSource==2====" + filePath);
        return filePath;
    }

    /**
     * 检查内存空间是否足够
     * @param entity
     * @return
     */
    public static boolean checkSize(MediaEntity entity) {
        String path = FileUtils.getPath(Constant.CACHE_FOLDER);
        File file = new File(path);
        long saved = 0l;
        if (file.exists())
            saved = FileUtils.getFolderSize(file);
        long free = FileUtils.getFreeSize();
        long videoFile = FileUtils.getFileSize(entity);
//        long total = free < 45 ? free : 45;
        long total = free < Constant.cacheSize ? free : Constant.cacheSize;
        long all = saved + videoFile;
//        Log.e(tag, "=checkSize====all======" + all);
//        Log.e(tag, "=checkSize====total======" + total);
        if (all > total){
            if (file.exists() && file.isDirectory()){
//                Log.e(tag, "=checkSize====length======" + file.listFiles().length);
                if (file.listFiles().length > 0){
                    File fi = file.listFiles()[0];
//                    Log.e(tag, "=checkSize====exists======" + fi.exists());
                    if (fi.exists()) {
                        boolean delete = fi.delete();
                        LogUtils.i(tag, "=====删除文件=====10=" + delete);
                        return checkSize(entity);
                    } else {
                        return false;
                    }
                } else {
                    Log.e(tag, "=checkSize====tush======");
                    AEvent.notifyListener(AEvent.TO_TOAST, true, "文件过大，内存空间不足");
                    return false;
                }
            }
            AEvent.notifyListener(AEvent.TO_TOAST, true, "文件过大，内存空间不足");
            return false;
        }
        return true;
    }

    /**
     * @return 获取文件路径
     */
    public static String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }
}
